﻿package com.codingbros.zigzag.lines{


	import flash.display.Shape;

	import flash.geom.Point;


	//zigzag line
	public final class MovingLine extends Shape implements ILine {

		private static const ZIGZAGWIDTHNUM:int=6;
		private static const ZIGZAGHEIGHTNUM:int=4;

		private static const POINTDISPLACEMENT:Number=3.5;

		private var myXPos:Number;
		private var myMaxX:Number;

		private var mySpeed:Number;
		private static const MINSPEED:Number=0.0005;
		private static const MAXSPEED:Number=1.0;
		
		private var COLORS:Array = new Array(0x000000, 0x1e2d44, 0x0e3e4f, 0xff1a32);
		private var myColor:uint;

		private var myZigZagPatternXSize:int;
		private var myZigZagPatternYSize:int;

		private var myPoints:Array;
		private var myCurrentPoint:int = 0;

		public function MovingLine(theParentWidth:int, theParentHeight:int) {
			myXPos=0;
			myMaxX=theParentWidth;
			mySpeed = MINSPEED + Math.random() * (MAXSPEED - MINSPEED);
			
			myColor = COLORS[Math.floor(Math.random()*4)];

			myZigZagPatternXSize=theParentWidth/ZIGZAGWIDTHNUM;
			myZigZagPatternYSize=theParentHeight/ZIGZAGHEIGHTNUM;

			myPoints=new Array(ZIGZAGWIDTHNUM+1);

			var lastYNum:Number=-1;

			for (var i:int = 0; i < myPoints.length; i ++) {
				var tempPoint:Point;
				var currentYNum:Number=Math.round(Math.random()*ZIGZAGHEIGHTNUM);
				while (currentYNum == lastYNum) {
					currentYNum=Math.round(Math.random()*ZIGZAGHEIGHTNUM);
				}
				lastYNum=currentYNum;
				var tempY:Number=currentYNum*myZigZagPatternYSize+Math.random()*POINTDISPLACEMENT;

				tempPoint=new Point(i*myZigZagPatternXSize+Math.random()*POINTDISPLACEMENT,tempY);
				myPoints[i]=tempPoint;
			}
		}

		public function update():void {
			if (myXPos<myMaxX) {
				myXPos+=mySpeed;
				if (myXPos>=myPoints[myCurrentPoint].x) {
					myCurrentPoint ++;
				}
			}
		}

		public function reset():void {

		}

		public function draw():void {
			this.graphics.clear();
			this.graphics.lineStyle(1, myColor, 0.5);
			this.graphics.moveTo(myPoints[0].x, myPoints[0].y);
			for (var i:int = 1; i < myCurrentPoint; i ++) 
			{
				this.graphics.lineTo(myPoints[i].x, myPoints[i].y);
			}
			if (myCurrentPoint > 0) 
			{
				this.graphics.lineTo(myXPos, myPoints[myCurrentPoint-1].y - (1- (myPoints[myCurrentPoint].x - myXPos)/myZigZagPatternXSize) * (myPoints[myCurrentPoint-1].y - myPoints[myCurrentPoint].y));
			}
			
		}
	}

}